<template>
  <div>
    <div class="page">
      <DynamicForm
        v-show="showSearch"
        ref="queryRef"
        v-model="queryParams"
        :config="formConfig"
        :items="formItems"
        :inline="true"
        @submit="handleQuery"
        @reset="resetQuery">
        <template #dateRange="{ formData }">
          <el-date-picker
            v-model="dateRange"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 18vw" />
        </template>
      </DynamicForm>
      <el-row :gutter="10" class="mb10">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['surveyInquiry:surveyInquiry:add']">
            新增
          </el-button>
          <el-button
            :disabled="exportDis"
            type="warning"
            plain
            icon="Plus"
            @click="handleExport"
            v-hasPermi="['surveyInquiry:surveyInquiry:export']">
            导出
          </el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
      </el-row>
      <Table
        v-loading="loading"
        :data="tableData"
        :columns="newColumns"
        @selection-change="handleSelectionChange"
        border>
        <template #index="{ $index }">
          {{ queryParams.pageNum * queryParams.pageSize - queryParams.pageSize + $index + 1 }}
        </template>
        <template #action="{ row }">
          <el-button
            icon="view"
            link
            type="primary"
            @click="handleEdit(row, 'view')"
            v-hasPermi="['surveyInquiry:surveyInquiry:query']">
            查看
          </el-button>
          <el-button
            v-hasPermi="['surveyInquiry:surveyInquiry:edit']"
            link
            icon="Edit"
            type="primary"
            @click="handleEdit(row, 'edit')">
            修改
          </el-button>
          <el-button icon="view" link type="primary" @click="handlePreview(row)">预览</el-button>
          <el-button icon="upload" link type="primary" @click="handleUpload(row)">上传附件</el-button>
          <el-button
            v-hasPermi="['surveyInquiry:surveyInquiry:remove']"
            icon="Delete"
            link
            type="danger"
            @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </Table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList" />
      <!-- 上传附件弹窗 -->
      <el-dialog title="上传附件" v-model="fileModal" width="1200px">
        <FileList v-if="fileModal" :fileUploadList="fileUploadList" />
        <template #footer>
          <div class="form-footer">
            <el-button type="primary" @click="handleUploadConfirm">保存</el-button>
            <el-button @click="() => (fileModal = false)">取消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import DynamicForm from '@/components/DynamicForm/index.vue'
import { ref, onMounted, computed } from 'vue'
import Table from '@/components/Table'
import { createInput, createSelect, createSlot } from '@/components/DynamicForm/config'
import { pageConfig } from './config'
import { useDeleteConfirm } from '@/hooks/useDeleteConfirm'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import FileList from '@/components/FileList/index.vue'
import {
  getInquiryList,
  previewInquiry,
  getInquiryDetail,
  addFiles,
  deleteInquiry,
  exportPenaltydecisions,
} from '@/api/inquiry/index'
import { downloadBlob } from '@/utils/download.js'

const { proxy } = getCurrentInstance()
const router = useRouter()

// 初始化删除确认 hook
const { confirmDeleteSingle, showDeleteConfirm } = useDeleteConfirm()
const showSearch = ref(true)
const dateRange = ref([])
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  partyName: undefined,
  caseNo: undefined,
  params: {
    beginCreateTime: undefined,
    endCreateTime: undefined,
  },
})

// 查询表单
const handleQuery = () => {
  getList()
}
// 重置表单
const resetQuery = () => {
  dateRange.value = null
  getList()
}

// 新增
const handleAdd = () => {
  router.push({
    path: '/workbench/inquiryDetail',
    query: {
      type: 'add',
    },
  })
}
// 导出
const exportDis = computed(() => {
  return Object.keys(selectedRows.value).length === 0
})
const handleExport = async () => {
  const _ids = ids.value
  const res = await exportPenaltydecisions(_ids)
  downloadBlob(res)
}

// 表格相关 start ======================================================
// 列显隐信息
const { formConfig, formItems, columns, newColumns } = pageConfig()
const loading = ref(false)
const tableData = ref([])
const total = ref(0)
// 获取表格数据
async function getList() {
  loading.value = true
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.value.params.beginCreateTime = dateRange.value[0]
    queryParams.value.params.endCreateTime = dateRange.value[1]
  } else {
    queryParams.value.params.beginCreateTime = undefined
    queryParams.value.params.endCreateTime = undefined
  }
  const res: any = await getInquiryList({ ...queryParams.value })
  tableData.value = res.rows || []
  total.value = res.total || 0
  loading.value = false
}
// 选择行
const selectedRows = ref<any>({})
const ids = ref([])
// 选择行变化
const handleSelectionChange = val => {
  ids.value = val.map(item => item.id)
  selectedRows.value = val
  console.log('选择行', selectedRows.value)
}
// 编辑 查看
const handleEdit = (row, type) => {
  console.log('编辑案件', row, type)
  router.push({
    path: '/workbench/inquiryDetail',
    query: {
      id: row.id || row.caseId,
      type,
    },
  })
}

// 删除案件的 API 函数
const deleteCase = async caseId => {
  // 模拟 API 调用
  await new Promise(resolve => setTimeout(resolve, 1000))
  console.log('删除案件 API 调用:', caseId)
  ElMessage.success('案件删除成功')
  // 删除后刷新列表
  await getList()
}
// 预览
const previewRow = ref(null)
const handlePreview = async row => {
  loading.value = true
  previewRow.value = row
  const res: any = await previewInquiry({ id: row.id })
  if (!!res.msg) {
    window.open(res.msg)
  } else {
    ElMessage.warning('预览文件不存在')
  }
  loading.value = false
}

// 上传附件
const fileModal = ref(false)
const fileUploadList = ref([])
const rowId = ref('')
const handleUpload = async row => {
  rowId.value = row.id
  const res = await getInquiryDetail(row.id)
  fileUploadList.value = res.data.tSurveyInquiryFilesList || []
  fileModal.value = true
}
const handleUploadConfirm = async () => {
  await addFiles({ id: rowId.value, tSurveyInquiryFilesList: fileUploadList.value })
  ElMessage.success('保存成功')
  fileModal.value = false
}

// 删除单个案件
const handleDelete = async row => {
  const _ids = row.id || ids.value
  proxy.$modal
    .confirm(`确定删除 "${row.partyName}" 的调查询问笔录？`)
    .then(function () {
      return deleteInquiry(_ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

// 表格相关 end ======================================================

onMounted(() => {
  getList()
})
</script>

<style scoped></style>
